package com.xingxing.Service;

import com.google.gson.Gson;
import com.xingxing.Bean.Likes;
import com.xingxing.Bean.Video;
import com.xingxing.Dao.LikesDao;
import com.xingxing.Dao.VideoDao;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @auther XingxingLu
 * @date 2022-06-08 10:53
 */
@WebServlet(name = "LikeVideo", value = "/LikeVideo")
public class LikeVideo extends HttpServlet {
    public LikeVideo() {
        super();
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        StringBuffer sb = new StringBuffer();
        BufferedReader br = new BufferedReader(
                new InputStreamReader((ServletInputStream) request.getInputStream(), "utf-8"));
        String temp;
        while ((temp = br.readLine()) != null) {
            sb.append(temp);
        }
        br.close();
        Map<String, Object> map = new HashMap<>();
        map = new Gson().fromJson(sb.toString(), map.getClass());
        if (map.get("type").equals("like")) {
            Likes like = new Likes((String) map.get("videoID"), (String) map.get("userAccount"));
            if (LikesDao.insert(like)) {
                map.put("status", "成功");
            }
            int count = LikesDao.findByVideoID((String) map.get("videoID")).size();
            map.put("count", Integer.toString(count));
        } else if (map.get("type").equals("disLike")) {
            Likes like = new Likes((String) map.get("videoID"), (String) map.get("userAccount"));
            if (LikesDao.insert(like)) {
                map.put("status", "成功");
            }
            int count = LikesDao.findByVideoID((String) map.get("videoID")).size();
            map.put("count", Integer.toString(count));
        } else if (map.get("type").equals("getCount")) {
            int count = LikesDao.findByVideoID((String) map.get("videoID")).size();
            map.put("count", Integer.toString(count));
        }
        String str = new Gson().toJson(map);
        out.println(str);
        out.flush();
        out.close();
    }

    public void init() throws ServletException {
    }

    public void destroy() {
        super.destroy();
    }
}
